import toast from 'react-hot-toast'
import { useState, useEffect, useContext, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useDebounce } from '@uidotdev/usehooks'
import { ThemeContext } from '../layouts/layout'
import { currentUserCan, getVulnerabilityStatusColor } from '../lib/utilities'
import { PencilSquareIcon, TrashIcon, BackspaceIcon } from '@heroicons/react/24/outline';
import '../styles/components/search-results.css';
import axios from 'axios'
import { 
  deleteProjectVulnerabilities, 
  fetchProjectFindings,
  searchVulnerabilities, 
  uploadProjectVulnerabilities, 
  updateVulnerabilityStatus,
  insertProjectVulnerability,
  getVulnerability,
  publishVulnerabilities
} from '../lib/data/api'
import DataTable from 'react-data-table-component'
import { Dialog, DialogHeader, DialogBody } from "@material-tailwind/react";
import { 
  Vulnerability, 
  VulnWithActions
} from '../lib/data/definitions'
import { TableColumn } from 'react-data-table-component'
import { 
  List, 
  ListItem, 
  Spinner
} from '@material-tailwind/react';
import { useVulnerabilityColor } from '../lib/customHooks';
import {  DocumentPlusIcon } from '@heroicons/react/24/outline';
import { StyleTextfield, ModalErrorMessage } from '../lib/formstyles';
import useCustomStyles from '../components/tableStyle'

// Ensure proper type casting for Material Tailwind components
const SpinnerIcon = Spinner as unknown as React.FC<React.HTMLAttributes<HTMLDivElement>>;
const ListComponent = List as unknown as React.FC<React.HTMLAttributes<HTMLUListElement>>;
const ListItemComponent = ListItem as unknown as React.FC<React.HTMLAttributes<HTMLLIElement>>;
const DialogComponent = Dialog as unknown as React.FC<{ handler: () => void; open: boolean; size: string; className: string; children: React.ReactNode }>;
const DialogHeaderComponent = DialogHeader as unknown as React.FC<React.HTMLAttributes<HTMLDivElement>>;
const DialogBodyComponent = DialogBody as unknown as React.FC<React.HTMLAttributes<HTMLDivElement>>;

interface VulnerabilityTableProps {
  projectId: number;
  projectStatus?: string;
  isProjectCompleted?: boolean;
  scopeCount?: number;
}

export default function VulnerabilityTable(props: VulnerabilityTableProps): JSX.Element {
  const {projectId, projectStatus, isProjectCompleted = false, scopeCount = 0} = props
  const [searchValue, setSearchValue] = useState('')
  const [selected, setSelected] = useState([])
  const debouncedValue = useDebounce<string>(searchValue, 500)
  const [spinner, setSpinner] = useState(false) //shows spinner for vulnerability search
  const navigate = useNavigate()
  const [searchResults, setSearchResults] = useState<{ id:number, vulnerabilityname: string }[]>([])
  const [showUploadCsv, setShowUploadCsv] = useState(false)
  const [findings, setFindings] = useState<Vulnerability[]>([])
  const [showStatusUpdate, setShowStatusUpdate] = useState(false)
  const canEdit = currentUserCan('Manage Projects')
  const theme = useContext(ThemeContext);
  const customStyles = useCustomStyles(theme);
  // Determine if vulnerabilities can be added (requires at least one scope)
  const noScopesExist = scopeCount === 0;

  async function deleteFinding(event:any, id:number | number[]): Promise<void> {
    // Prevent action if project is completed or no scopes exist
    if (isProjectCompleted) {
      toast.error('Cannot modify vulnerabilities for completed projects');
      return;
    }
    
    if (noScopesExist) {
      toast.error('Cannot modify vulnerabilities when no scopes are defined');
      return;
    }
    
    let toDelete:number[] = []
    if(typeof id === 'number'){
      toDelete.push(id)
    } else {
      toDelete = id
    }
    event.stopPropagation()
    if (!confirm('Are you sure?')) {
      return;
    }
    try {
      await deleteProjectVulnerabilities(toDelete)
      loadFindings()
      toast.success('Vulnerability deleted')
    } catch(error){
      console.error(error)
      toast.error(String(error))
    }
  }
  const loadFindings = async () => {
    const _findings = await fetchProjectFindings(String(projectId)) as VulnWithActions[]
    let temp = formatRows(_findings)
    setFindings(temp)
  }
  useEffect(() => {
    loadFindings()
  }, [projectId])

  // Re-format rows when project status changes
  useEffect(() => {
    if (findings.length > 0) {
      const updatedFindings = formatRows([...findings]);
      setFindings(updatedFindings);
    }
  }, [isProjectCompleted]);

  const onRowClicked = (row:any) => navigate(`/projects/${projectId}/vulnerability/view/${row.id}`);
  function formatRows(rows: VulnWithActions[]):VulnWithActions[] {
    let temp: any = []
    rows.forEach((row: VulnWithActions) => {
      // If project is completed or no scopes exist, don't add edit/delete actions
      if (isProjectCompleted || noScopesExist) {
        row.actions = <span className="text-gray-400 italic text-xs">No actions available</span>;
      } else {
        row.actions = (<>
                      <PencilSquareIcon onClick={() => navigate(`/projects/${projectId}/vulnerability/edit/${row.id}`)} className="inline w-6 cursor-pointer"/>
                      <TrashIcon onClick={(event) => deleteFinding(event,row.id as number)} className="inline w-6 ml-2 cursor-pointer" />                        
                      </>);
      }
      const [meaning, color] = useVulnerabilityColor(row.vulnerabilityseverity as string)
      row.severity = (<span className={`text-[${color}]`}>{meaning}</span>)
      temp.push(row)
    });
    return temp;
  
  }
  const columns: TableColumn<VulnWithActions>[] = [
    ...(canEdit ? [{
      name: 'Action',
      cell: (row: VulnWithActions) => row.actions,
     
      maxWidth: '1rem'
    }] : []),
    {
      name: 'Name',
      selector: (row: VulnWithActions) => row.vulnerabilityname,
      sortable: true
    },
    ...(projectId ? [{
      name: 'Status',
      cell: (row: VulnWithActions) => <span className={getVulnerabilityStatusColor(row.status as string )}>{row.status}</span>,
      maxWidth: '10em',
      sortable: true,
      selector: (row: VulnWithActions) => row.status as string || '',
      sortFunction: (a: VulnWithActions, b: VulnWithActions) => (a.status ?? '').localeCompare(b.status ?? ''),
    }] : []),
    {
      name: 'Severity',
      cell: (row: VulnWithActions) => row.severity,
      maxWidth: '10em',
      sortable: true,
      sortFunction: (a: VulnWithActions, b: VulnWithActions) => (a.vulnerabilityseverity ?? '').localeCompare(b.vulnerabilityseverity ?? ''),
    },
    {
      name: 'Score',
      selector: (row: VulnWithActions) => row.cvssscore ?? 0,
      maxWidth: '5em',
      sortable: true
    },
    {
      name: 'Published',
      selector: (row: VulnWithActions) => (row.published ? 'Yes' : 'No'),
      
      maxWidth: '10em',
      sortable: true
    },
    {
      name: 'Created By',
      selector: (row: VulnWithActions) => row.created_by|| '',
      maxWidth: '12em',
      sortable: true
    },
    {
      name: 'Last Updated By',
      selector: (row: VulnWithActions) => row.last_updated_by|| '',
      maxWidth: '12em',
      sortable: true
    },
  ]
  // recursive function to generate a unique name for a new vulnerability that doesn't clash with existing ones in findings
  function generateUniqueName(): string {
    const tempName = "New Vulnerability " + Math.floor(Math.random() * 100);
    if (findings.some((item: { vulnerabilityname: string }) => item.vulnerabilityname === tempName)) {
      return generateUniqueName(); // Recursively call if name exists
    }
    return tempName;
  }
  const handleSelectedSearchItem = (vid:string | number, name: string = '') => {
    // Prevent action if project is completed
    if (isProjectCompleted) {
      toast.error('Cannot add vulnerabilities to completed projects');
      return;
    }
    
    // Prevent action if no scopes exist
    if (noScopesExist) {
      toast.error('Cannot add vulnerabilities when no scopes are defined');
      return;
    }
    
    setSearchValue(name.trim())
    setSpinner(true)
    
    if(vid==='new'){
      const tempName = generateUniqueName()
      const toInsert = {
        project: projectId,
        vulnerabilityname: tempName,
        instance: []
      }
      insertProjectVulnerability(toInsert).then((data)=>{
        navigate(`/projects/${projectId}/vulnerability/edit/${data.id}`)
      })
    } else if (vid) {
      const selectedItem = searchResults.find(item => item.id === vid)
      if (selectedItem) {
        setSpinner(true)
        getVulnerability(String(selectedItem.id))
        .then((data)=>{
          const toInsert = {
            ...data,
            project: projectId,
            instance: []
          }
          insertProjectVulnerability(toInsert).then((data)=>{
            toast.success('Vulnerability added')
            navigate(`/projects/${projectId}/vulnerability/edit/${data.id}/poc`)
            
          })
        }).catch((error)=>{
          console.error(error)
          toast.error(String(error))
        }).finally(()=>{
          setSpinner(false)
        })
      }
    }
    setSearchResults([])
  }
  async function deleteMultiple(event:any){
    // Prevent action if project is completed
    if (isProjectCompleted) {
      toast.error('Cannot delete vulnerabilities from completed projects');
      return;
    }
    
    // Prevent action if no scopes exist
    if (noScopesExist) {
      toast.error('Cannot delete vulnerabilities when no scopes are defined');
      return;
    }
    
    event.stopPropagation()
    if(selected.length == 0){
      toast.error('Please select at least one vulnerability to delete')
      return
    }
    await deleteFinding(event, selected)
    setSelected([])
  }  
  const handlePublish = async (publish: boolean) => {
    // Prevent action if project is completed
    if (isProjectCompleted) {
      toast.error(`Cannot ${publish ? 'publish' : 'unpublish'} vulnerabilities for completed projects`);
      return;
    }
    
    // Prevent action if no scopes exist
    if (noScopesExist) {
      toast.error(`Cannot ${publish ? 'publish' : 'unpublish'} vulnerabilities when no scopes are defined`);
      return;
    }
    
    try {
      if (selected.length === 0) {
        toast.error('Please select at least one vulnerability to proceed');
        return;
      }
      const action = publish ? 'published' : 'unpublished';
      await publishVulnerabilities(selected, publish);
      toast.success(`Successfully ${action} ${selected.length} vulnerabilities`);
      loadFindings();
    } catch (error: any) {
      console.error(error);
      
      // Check if it's an Axios error with response data
      if (axios.isAxiosError(error) && error.response?.data) {
        const errorData = error.response.data;
        
        // Check for the specific "Cannot publish vulnerabilities without instances" error
        if (errorData.error === "Cannot publish vulnerabilities without instances" && errorData.affected_vulnerabilities) {
          // Format the error message to show which vulnerabilities need instances
          toast.error(
            <div>
              <p>Failed to publish: Some vulnerabilities have no instances.</p>
              <p className="mt-2 font-semibold">Affected vulnerabilities:</p>
              <ul className="list-disc ml-4 mt-1">
                {errorData.affected_vulnerabilities.map((item: any) => (
                  <li key={item.id}>{item.name}</li>
                ))}
              </ul>
              <p className="mt-2 text-sm">Please add at least one instance to each vulnerability before publishing.</p>
            </div>,
            { duration: 6000 }
          );
          return;
        }
      }
      
      // Default error handling
      toast.error(String(error));
    }
  };
  const handleSelectedRowsChange = (event: any) => {
    const ids = event.selectedRows.map((item:any) => item.id)
    setSelected(ids)
  }
  
  const toggleShowUploadCsv = (event:any) => {
    // Prevent action if project is completed
    if (isProjectCompleted) {
      toast.error('Cannot upload CSV for completed projects');
      return;
    }
    
    // Prevent action if no scopes exist
    if (noScopesExist) {
      toast.error('Cannot upload CSV when no scopes are defined');
      return;
    }
    
    event.stopPropagation()
    event.preventDefault()
    setShowUploadCsv(!showUploadCsv)
  }
  useEffect(() => {
    if(debouncedValue){
      setSpinner(true)
      searchVulnerabilities(debouncedValue).then((data) => {
        //filter out the ones that are already in the project
        const filteredData = data.filter((item: { vulnerabilityname: string }) => {
          return !findings.some((finding) => finding.vulnerabilityname === item.vulnerabilityname)
        });
        setSearchResults(filteredData);
      }).catch((error) => {
        console.error(error)
        // toast.error(error.)
      }).finally(() => {
        setSpinner(false)
      })
    }
  }, [debouncedValue])
  const clearSearch = () => {
    setSearchValue('')
    setSearchResults([])
  }
  const handleNameSearch = (event:any) => {
    setSearchValue(event.target.value)
    if(event.target.value==''){
      setSearchResults([])
    }
  }
  const refreshAfterStatusChange = () => {
    loadFindings()
    setShowStatusUpdate(false)
  }

  // Display project status warning if completed
  const ProjectCompletedWarning = () => {
    if (isProjectCompleted) {
      return (
        <div className="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4">
          <div className="flex">
            <div className="ml-3">
              <p className="text-sm text-yellow-700">
                This project is marked as Completed. Vulnerabilities cannot be modified.
              </p>
            </div>
          </div>
        </div>
      );
    }
    return null;
  };

  // Display warning when no scopes exist
  const NoScopesWarning = () => {
    if (noScopesExist && !isProjectCompleted) {
      return (
        <div className="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4 dark:bg-gray-400 ">
          <div className="flex">
            <div className="ml-3">
              <p className="text-sm text-yellow-700 dark:text-red-800">
                No scopes have been defined for this project. Please add at least one scope before adding vulnerabilities.
              </p>
            </div>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
          <>
            <ProjectCompletedWarning />
            <NoScopesWarning />
            
            {currentUserCan('Manage Projects') && !isProjectCompleted && !noScopesExist &&
              <div className="relative max-w-xl">
                <input 
                  list="searchResults" 
                  placeholder='Search & add' value={searchValue} 
                  className="dark:bg-gray-800 dark:text-white border border-gray-200 p-2 rounded-md w-3/4" 
                  type="text" 
                  onChange={handleNameSearch} 
                />
                {spinner && <SpinnerIcon className="h-6 w-6 -ml-8 inline mr-2" />}
                {!spinner && searchValue && <BackspaceIcon onClick={clearSearch} className="text-secondary w-6 h-6 inline -ml-8 mr-2" />}
                    <ListComponent 
                  className={`
                    max-w-xl absolute bg-white border dark:bg-gray-800 dark:text-white 
                    border-t-0 -mt-0.50 pt-2 border-gray-200 p-0 rounded-b-md z-10
                    max-h-64 overflow-y-auto scrollable-results
                    ${searchValue && searchResults.length > 0 ? 'block' : 'hidden'}
                  `} 
                  key='searchResults'
                >                    {searchValue && searchResults.length > 0 ? (
                      <>
                        {/* Results counter */}
                        <div className="text-xs px-3 py-1 text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-gray-700">
                          Found {searchResults.length} {searchResults.length === 1 ? 'result' : 'results'}
                        </div>
                        
                        {/* Results list */}
                        {searchResults.map((item) => {
                          return <div key={`search-${item.id}`}>
                            <ListItemComponent 
                              onClick={()=>handleSelectedSearchItem(item?.id, item?.vulnerabilityname)}
                              className="hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer transition-colors py-2"
                            >
                              <DocumentPlusIcon className="h-6 w-6 mr-1 flex-shrink-0"/>
                              <span className="overflow-hidden text-ellipsis">{item?.vulnerabilityname}</span>
                            </ListItemComponent>
                          </div>
                        })}
                      </>
                    ) : (
                      searchValue && (
                        <div className="p-3 text-center text-gray-500 dark:text-gray-400">
                          No matching vulnerabilities found
                        </div>
                      )
                    )}
                    
                    {searchValue && searchResults.length > 8 && (
                      <div className="text-xs text-center py-1 text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700">
                        Scroll to see more results
                      </div>
                    )}
                </ListComponent>
                
                {!showUploadCsv &&
                      <div className='mt-2'>
                        <button key='addNewVulnerability' className='bg-primary text-white p-2 rounded-md ml-0' onClick={()=>handleSelectedSearchItem('new')}>Add New</button>
                        <span className='mx-2 dark:text-white'>or</span>
                        <button className='ml-1 mt-2 cursor-pointer bg-secondary text-white p-2 rounded-md' onClick={toggleShowUploadCsv}>
                            Upload CSV
                        </button>
                      </div>
                }
                
                <div className='mt-4'>
                <CSVInput projectId={projectId} visible={showUploadCsv} hide={toggleShowUploadCsv} afterUpload={()=>loadFindings()} afterUploadError={(error)=>toast.error(String(error))} isProjectCompleted={isProjectCompleted} noScopesExist={noScopesExist}/>
                
                </div>
              </div>
            }           
            <div className='w-full relative'>
              {currentUserCan('Manage Projects') && !isProjectCompleted && !noScopesExist &&
              <>
                
                <button  
                  className='bg-secondary float-right p-2 text-white rounded-md disabled:opacity-50 '
                  disabled={selected.length === 0}
                  onClick = {deleteMultiple}
                >
                  Delete
                </button>
                <button  
                  className='bg-primary float-right p-2 text-white rounded-md disabled:opacity-50 mr-2 mb-2'
                  disabled={selected.length === 0}
                  onClick = {() => setShowStatusUpdate(true)}
                >
                  Update Status
                </button>
                <button  
                  className='bg-primary float-right p-2 text-white rounded-md disabled:opacity-50 mr-2 mb-2'
                  disabled={selected.length === 0}
                  onClick = {() => handlePublish(true)}
                >
                  Publish
                </button>
                <button  
                  className='bg-secondary float-right p-2 text-white rounded-md disabled:opacity-50 mr-2 mb-2'
                  disabled={selected.length === 0}
                  onClick = {() => handlePublish(false)}
                >
                  Unpublish
                </button>
                {showStatusUpdate && <StatusUpdateForm selected={selected} afterSave={refreshAfterStatusChange} isProjectCompleted={isProjectCompleted} noScopesExist={noScopesExist} />}
              </>
              }
              <DataTable
                columns={columns}
                data={findings}
                pagination
                paginationPerPage={10}
                onRowClicked={onRowClicked}
                striped
                onSelectedRowsChange={handleSelectedRowsChange}
                theme={theme}
                customStyles={customStyles}
                {...(currentUserCan('Manage Projects') && !isProjectCompleted && !noScopesExist ? { selectableRows: true } : {})}
                />
              
            </div>
          </>
  )
}

interface StatusUpdateProps {
  selected: number[]
  afterSave: () => void
  isProjectCompleted?: boolean
  noScopesExist?: boolean
}
const StatusUpdateForm = ({selected, afterSave, isProjectCompleted = false, noScopesExist = false}: StatusUpdateProps): JSX.Element => {
  const [error, setError] = useState('')
  const handleClose = () => {
    afterSave()
  }
  const cancel = () => {
    afterSave()
  }
  const [status, setStatus] = useState('')
  const handleStatusChange = (event: any) => {
    setStatus(event.target.value)
  }
  const handleSave = async (event: any) => {
    event.preventDefault()
    
    if (isProjectCompleted) {
      setError('Cannot update vulnerability status for completed projects');
      return;
    }
    
    if (noScopesExist) {
      setError('Cannot update vulnerability status when no scopes are defined');
      return;
    }
    
    if(!status){
      setError('Please choose a status')
      return
    }
    setError('')
    try {
      if(selected.length == 1){
        await updateVulnerabilityStatus(selected[0], status)
        toast.success(`Status updated for ${selected.length} vulnerabilities`)
      } else {
        await Promise.all(selected.map(id => updateVulnerabilityStatus(id, status)))
        toast.success(`Status updated for ${selected.length} vulnerabilities`)
      }
      afterSave()
    } catch(error) {
      const err = error as { response?: { data?: { message?: string } } }
      const msg = err.response?.data?.message ?? String(error)
      console.error(error)
      setError('Error: ' + msg)
    }
    
  }
  return (           
            <DialogComponent handler={handleClose} open={true} size="sm" className="modal-box w-[500px] bg-white p-4 rounded-md dark:bg-gray-800" >
              {error && <ModalErrorMessage message={error} />}
              <DialogHeaderComponent className='dark:text-white'>Update Status for {selected.length} vulnerabilities</DialogHeaderComponent>
              <DialogBodyComponent>
                <form onSubmit={handleSave}>
                  <select 
                    name="status" 
                    value={status} 
                    onChange={handleStatusChange}
                    disabled={isProjectCompleted || noScopesExist}
                    className={`${StyleTextfield} ${(isProjectCompleted || noScopesExist) ? 'opacity-75 cursor-not-allowed' : ''}`}
                  >
                    <option className="dark:bg-gray-800 dark:text-white" value="">Select Status</option>
                    <option className="dark:bg-gray-800 dark:text-white" value="Vulnerable"> Vulnerable</option>
                    <option className="dark:bg-gray-800 dark:text-white" value="Confirm Fixed">Confirm Fixed</option>
                    <option className="dark:bg-gray-800 dark:text-white" value="Accepted Risk">Accepted Risk</option>
                  </select>
                  <div className='mt-4'>
                    <button 
                      type="submit" 
                      onClick={handleSave} 
                      disabled={isProjectCompleted || noScopesExist}
                      className={`bg-primary text-white p-2 rounded-md mt-2 mr-2 ${(isProjectCompleted || noScopesExist) ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                      Update
                    </button>
                    <span className='underline cursor-pointer text-secondary' onClick={cancel}>cancel</span>
                  </div>
                  {isProjectCompleted && 
                    <div className='text-red-500 mt-2'>
                      Cannot update vulnerability status for completed projects
                    </div>
                  }
                  {noScopesExist && !isProjectCompleted && 
                    <div className='text-red-500 mt-2'>
                      Cannot update vulnerability status when no scopes are defined
                    </div>
                  }
                </form>
              </DialogBodyComponent>
            </DialogComponent>
  )
}
interface CSVInputProps {
  projectId: number
  visible: boolean
  hide: (event: any) => void
  afterUpload: (data: any) => void
  afterUploadError: (error: any) => void
  isProjectCompleted?: boolean
  noScopesExist?: boolean
}

const CSVInput = ({projectId, visible = false, hide, afterUpload, afterUploadError, isProjectCompleted = false, noScopesExist = false}: CSVInputProps): JSX.Element => {
  // /api/project/vulnerability/Nessus/csv/<project-id>/
  const fileInput = useRef<HTMLInputElement>(null)
  const [csvFileName, setCsvFileName] = useState('')
  const [csvFile, setCsvFile] = useState<File | null>(null)
  useEffect(() => {
    if(visible){
      setCsvFileName('')
      setCsvFile(null)
    }
  }, [visible])
  const handleFile = (event:any) => {
    setCsvFileName(event.target.files[0].name)
    setCsvFile(event.target.files[0])
    
  }
  const resetUploader = () => {
    setCsvFileName('')
    setCsvFile(null)
    if(fileInput.current){
      fileInput.current.value = ''
    }
  }
  const deleteCsvFile = () => {
    resetUploader()
  }
  const handleCSVUpload = async () : Promise<void> => {
    if (isProjectCompleted) {
      toast.error('Cannot upload CSV for completed projects');
      return;
    }
    
    if (noScopesExist) {
      toast.error('Cannot upload CSV when no scopes are defined');
      return;
    }
    
    if(csvFile){
      try {
        const result = await uploadProjectVulnerabilities(projectId, csvFile)
        toast.success('Upload complete')
        resetUploader()
        afterUpload(result)
      } catch(error){
        console.error(error)
        toast.error(String(error))
        afterUploadError(error)
      }
    }
    
  }
  if(!visible){
    return <></>
  }
  return (
    <>
      <p className='text-sm my-2 dark:text-white'>
        Click <span className='font-bold dark:text-white'>Choose File</span> to select a CSV or <span className='underline cursor-pointer text-secondary' onClick={hide}>Cancel</span>
      </p>
      <input type="file"
        id="csv"
        key="csv"
        name="csv"
        accept="text/csv"
        onChange={handleFile}
        ref={fileInput}
        disabled={isProjectCompleted || noScopesExist}
        className={`text-sm text-white
                  file:text-white
                    file:mr-5 file:py-2 file:px-6
                    file:rounded-full file:border-0
                    file:text-sm file:font-medium
                    file:bg-primary
                    file:cursor-pointer
                    ${csvFile || isProjectCompleted || noScopesExist ? 'opacity-75' : ''}
                    ${isProjectCompleted || noScopesExist ? 'cursor-not-allowed' : ''}
                    hover:file:bg-secondary`}
      />
      {csvFileName && !(isProjectCompleted || noScopesExist) && 
        <>
        <div className='text-md text-primary mt-2 ml-2'>
          <BackspaceIcon className="w-4 h-4 inline mr-2 text-secondary" onClick={deleteCsvFile}/>
          {csvFileName}
        </div>
        <button className='bg-secondary text-sm text-white p-2 rounded-full block mt-4' onClick={handleCSVUpload}>Upload Now</button>
        </>
      }
      {isProjectCompleted &&
        <div className='text-md text-red-500 mt-2 ml-2'>
          CSV upload is disabled for completed projects
        </div>
      }
      {noScopesExist && !isProjectCompleted &&
        <div className='text-md text-red-500 mt-2 ml-2'>
          CSV upload is disabled when no scopes are defined
        </div>
      }
    </>
  )
}
